package stc.skymobi.netty.initializer;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import stc.skymobi.netty.handler.codec.http.HttpResponseHandler;
import stc.skymobi.netty.handler.codec.http.ssl.HttpSslContextFactory;

import javax.net.ssl.SSLEngine;

public class HttpClientInitializer extends BaseInitializer {

    private HttpResponseHandler httpResponseHandler;

    private ChannelHandler nettyEncoder;
    private ChannelHandler nettyDecoder;

    //一个HTTP传输的最大数据量,默认1G
    private int maxContentLength = 1024 * 1024 * 1024;
    //Raises a ReadTimeoutException when no data was read within a certain period of time.
    private int readTimeoutSeconds = 0;
    private boolean useSsl; //是否使用https

    @Override
    public void addCodecHandler(ChannelPipeline pipeline) throws Exception {
        if (useSsl) {
            SSLEngine engine =
                    HttpSslContextFactory.getClientContext().createSSLEngine();
            engine.setUseClientMode(true);
            pipeline.addLast("ssl", new SslHandler(engine));
        }
        if(readTimeoutSeconds > 0){
            pipeline.addLast(new ReadTimeoutHandler(readTimeoutSeconds));
        }
        pipeline.addLast("codec", new HttpClientCodec())
                .addLast("aggregator", new HttpObjectAggregator(maxContentLength));
        if (nettyEncoder != null) {
            pipeline.addLast("nettyEncoder", nettyEncoder);
        }
        if (nettyDecoder != null) {
            pipeline.addLast("nettyDecoder", nettyDecoder);
        }
    }

    @Override
    protected void addBusinessHandler(ChannelPipeline pipeline) throws Exception {
        pipeline.addLast("handler", httpResponseHandler);
    }

    public void setHttpResponseHandler(HttpResponseHandler httpResponseHandler) {
        this.httpResponseHandler = httpResponseHandler;
    }

    public void setNettyEncoder(ChannelHandler nettyEncoder) {
        this.nettyEncoder = nettyEncoder;
    }

    public void setNettyDecoder(ChannelHandler nettyDecoder) {
        this.nettyDecoder = nettyDecoder;
    }

    public void setMaxContentLength(int maxContentLength) {
        this.maxContentLength = maxContentLength;
    }

    public boolean isUseSsl() {
        return useSsl;
    }

    public void setUseSsl(boolean useSsl) {
        this.useSsl = useSsl;
    }

    public int getReadTimeoutSeconds() {
        return readTimeoutSeconds;
    }

    public void setReadTimeoutSeconds(int readTimeoutSeconds) {
        this.readTimeoutSeconds = readTimeoutSeconds;
    }
}
